/**
 * 
 */
package ro.dta.idbi.interfaces.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.mxgraph.io.mxCodec;
import com.mxgraph.swing.mxGraphComponent;

import ro.dta.idbi.interfaces.ISaveStrategy;

/**
 * Abstract diagram, implemented using the JGraph public library
 * 
 * @author Tudor Dobrila
 * 
 */
public abstract class AbstractDiagram extends JPanel {

	private static final long serialVersionUID = 425755231023048695L;

	/**
	 * Parent frame of the application
	 */
	protected IMainFrame parentFrame;

	/**
	 * Graph component holding the diagram
	 */
	protected mxGraphComponent graphComponent;

	/**
	 * Abstract diagram class constructor
	 * 
	 * @param parentFrame
	 *            Parent frame of the application
	 */
	public AbstractDiagram(IMainFrame parentFrame) {
		this.parentFrame = parentFrame;
	}

	/**
	 * Save a diagram
	 * 
	 * @param saveStrategy
	 *            File save strategy
	 * @return True if the diagram has been saved successfully, false otherwise
	 */
	public boolean save(ISaveStrategy saveStrategy) {
		final JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(new File("."));
		chooser.setFileFilter(saveStrategy.getFileFilter());
		chooser.setMultiSelectionEnabled(false);
		final int returnVal = chooser.showSaveDialog(this);
		boolean result = false;

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			String path = chooser.getSelectedFile().getAbsolutePath();
			if (!path.endsWith(saveStrategy.getExtension())) {
				path += saveStrategy.getExtension();
			}
			File savePath = new File(path);

			if (!savePath.exists()
					|| (savePath.exists() && JOptionPane.showConfirmDialog(this,
							"Overwrite existing file?", "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)) {

				try {
					saveStrategy.save(graphComponent, getCodec(), path);
					parentFrame.setStatusBarText("Strategy diagram saved to " + path);
				} catch (FileNotFoundException e) {
					JOptionPane.showMessageDialog(this,
							"Could not save diagram. Reason:\r\n" + e.getMessage(), "Error",
							JOptionPane.ERROR_MESSAGE);
				} catch (IOException e) {
					JOptionPane.showMessageDialog(
							this,
							"An error occured while saving the diagram. Reason:\r\n"
									+ e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
		}

		return result;
	}

	/**
	 * Get the codec of the diagram
	 */
	public abstract mxCodec getCodec();

}
